package com.bs.areport.action.basic;
/** 
 * 基础资料导入导出
 * @ClassName   类名：DownloadAction 
 * @Description 功能说明：
 * TODO
 ************************************************************************
 * @date        创建日期：2012-8-10
 * @author      创建人：陈金滨
 * @version     版本号：V1.0
 ***************************修订记录*************************************
 * 
 *   2012-8-10  陈金滨  创建类
 *
 ***********************************************************************
 */
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.bs.areport.service.util.EntityType;
import com.bs.areport.service.util.MethodUtil;
import com.bs.areport.service.master.UserManageDao;
import com.bs.restframework.context.SystemContext;
import com.bs.restframework.context.util.SystemContextUtil;
import com.bs.restframework.db.Database;
import com.bs.restframework.session.UserSession;
import com.bs.restframework.web.action.BaseAction;
import com.bs.restframework.web.result.ResultModle;
import com.bs.restframework.web.result.ResultType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


@SuppressWarnings("unused")
public class ExcelsAction extends BaseAction
{
	
	/**	  
	 * <p>函数名称：判断文件格式是否正确</p>
	 * <p>创建时间：2012-08-08</p>
	 * <p>作者：陈金滨</p>
	 */
	//ClassPathResource cpr = new ClassPathResource("com.bs.ddd.dsd"); 取类路径
	private Map<String,String> checkFile(File file,String contentType){			
		Map<String,String> map =new HashMap<String,String>();
		String msg="";
		
		if(file==null){
			msg="请选择文件.";			
		}else {
			String filename= contentType.toLowerCase();
			if("".equals(msg))
			{
				if(!filename.endsWith("excel") && !filename.endsWith("EXCEL")){
					msg="文件类型不正确,限.xls、.XLS文件";
				}else{
					if(filename.equals("xls")){
						map.put("fileType", ".xls");
					}else if(filename.equals("XLS")){
						map.put("fileType", ".XLS");
					}
				}				
			}
			
			if(filename.endsWith("stream"))
				msg = "该文件正在使用中，请关闭后重新导入" ;			
		}
		map.put("msg", msg);
		return map;
	}

	/**	  
	 * <p>函数名称：上传文件</p>
	 * <p>创建时间：2012-08-08</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle uploadFile() throws Exception{
		
		//获取文件
		Map<String,Object> params=SystemContext.getInParams();
		File file = (File)params.get("file");
		String tableName = (String) params.get("tableName") ;
		//获取文件类型
		String contentType=(String) params.get("contentType");
		Database db = SystemContextUtil.getDatabase(this);
		String vJC = "" ;
		if("ARP_BSC_DEPT".equals(tableName))
		{
			vJC = MethodUtil.getDeptJC(db);
			
		}else if("ARP_BSC_CHARGE".equals(tableName))
		{
			vJC = MethodUtil.getCharghJC(db);
		}
		

		//当前系统时间为文件名
        Date currentTime = new Date();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsssss");
	    String dateString = formatter.format(currentTime);				
		
	    //将文件拷贝到默认文件夹
		File newFile = new File(ServletActionContext.getServletContext().getRealPath("")
				+ "/upload/"+ dateString+".xls");		
		
		FileOutputStream fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("")
				+ "/upload/" + dateString+".xls");

		FileInputStream fis = new FileInputStream(file);
		
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) 
		{
		fos.write(buffer, 0, len);
		}		
		fis.close();
		fos.close();	
		
		Map<String,Object>  result = new HashMap<String, Object>();		
		
		//判断文件类型
		try{
			Map<String,String> map=checkFile(file,contentType);			
			//如果文件类型正确
			if(map.get("msg").length()==0){
                String msg = "" ;
				//执行数据导入动作
				msg = MethodUtil.excelToDB(tableName,dateString,db,vJC);
				if("".equals(msg))
				{
					//移动文件
					FileUtils.copyFile(file, newFile);
					result.put("msg","导入数据成功!");
					result.put("tag", true) ;		
					
				}else{
					result.put("msg",msg);
					result.put("tag", true) ;
				}
				
			}else{
				result.put("msg", map.get("msg"));
				result.put("tag", false);
			}
		}catch (Exception e) {
			result.put("tag", false);
			result.put("msg",e.getMessage());
			e.printStackTrace();
		}
//		String toURL = ""; 
//		if("导入数据成功!".equals(result.get("msg")))
//			toURL = "/pages/basic/master/success";		    
//		else
//			toURL = "/pages/basic/master/importError" ;
//		return new ResultModle(ResultType.OUTPUT_JSP_VIEW, toURL, result);	
		return new ResultModle(ResultType.OUTPUT_JSON_STREAM,"user",result);
	}	


	/**	  
	 * <p>函数名称：下载文件</p>
	 * <p>创建时间：2012-08-08</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle download() throws Exception{
		//获取表名
		Database db = SystemContextUtil.getDatabase(this);
		Map<String,Object> params=SystemContext.getInParams();
		String tableName = (String) params.get("tableName") ;
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String userType = userSession.getUserType().toString() ;
		String deptID = "" ;
		
		if(!"A".equals(userType))
		  deptID = userSession.getAttribute("deptID").toString() ;
		
		String deptCode = "ALLDEPT" ;
		if(!"".equals(deptID))
		{
			String sql= "SELECT * FROM "+EntityType.ARP_BSC_DEPT_TABLE +" WHERE F_ID='"+deptID+"'";
			Map<String, Object> vMap=db.queryObject(Map.class, sql, null);
			if(vMap!=null)
			  deptCode = (String) vMap.get("F_CODE") ;	
		}	
		
		String fName = "" ;		
		//获取生成文件名
		if(tableName==null||"".equals(tableName))
			tableName = "ARP_BSC_DEPT" ;
		if("ARP_BSC_DEPT".equals(tableName))
			fName = "DEPT.xls" ;
		else
			fName = "CHARGE.xls" ;
		String fileName = MethodUtil.getExcel(tableName,deptCode,db);
		//去数据流
		InputStream in = null;
		
		ClassPathResource filePath = new ClassPathResource("com/bs/areport/action");
		String filePaths= filePath.getPath();
		 
		System.out.println(ServletActionContext
				.getServletContext().getRealPath("")
				+ "/upload/" + fileName);
		try {
			in = new FileInputStream(ServletActionContext
					.getServletContext().getRealPath("")
					+ "/upload/" + fileName);
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(in);
	return new ResultModle(fName,in);
  }
	
	/**	  
	 * <p>函数名称：下载文件</p>
	 * <p>创建时间：2012-08-08</p>
	 * <p>作者：陈金滨</p>
	 */
	public ResultModle getUserType() throws Exception{
		
		Map<String, Object> params = SystemContext.getInParams();		
		String token =(String)params.get("Token");
		UserSession userSession = SystemContextUtil.getSessionMange().getUserSession((String)params.get("Token"));
		String userID = userSession.getUserID().toString();		
        String userType = userSession.getUserType().toString();	

		Map<String, Object> resultBean=new HashMap<String, Object>();
		resultBean.put("USERTYPE", userType);

		return new ResultModle(ResultType.OUTPUT_JSON_STREAM, "user", resultBean);
		
	}	
	
}
